package com.jiaoyou.baojian.activity;

import android.content.Intent;
import android.database.Cursor;
import android.media.MediaPlayer;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.provider.MediaStore;
import android.support.annotation.Nullable;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.alibaba.sdk.android.push.CommonCallback;
import com.google.gson.Gson;
import com.jiaoyou.baojian.BaojianApplication;
import com.jiaoyou.baojian.R;
import com.jiaoyou.baojian.agora.AgoraHelper;
import com.jiaoyou.baojian.agora.ChannelAttr;
import com.jiaoyou.baojian.agora.ChannelMsg;
import com.jiaoyou.baojian.constvalue.ConstValue;
import com.jiaoyou.baojian.dialog.ImageSelectDialog;
import com.jiaoyou.baojian.dialog.LoadingDialog;
import com.jiaoyou.baojian.dialog.OkDialog;
import com.jiaoyou.baojian.dialog.SendGiftsDialog;
import com.jiaoyou.baojian.dialog.YesOrNoDialog;
import com.jiaoyou.baojian.entity.response.LoginResponse;
import com.jiaoyou.baojian.http.Api;
import com.jiaoyou.baojian.otto.AppBus;
import com.jiaoyou.baojian.otto.Event;
import com.jiaoyou.baojian.utils.ACache;
import com.jiaoyou.baojian.wiget.CustomToast;
import com.umeng.analytics.MobclickAgent;

import java.io.File;
import java.io.IOException;

import io.agora.AgoraAPI;
import io.agora.AgoraAPIOnlySignal;
import io.agora.IAgoraAPI;
import io.agora.rtc.IRtcEngineEventHandler;
import io.agora.rtc.RtcEngine;

/**
 * Created by hzzhangyumin on 2016/4/23.
 */
public abstract class BaseActivity extends AppCompatActivity {

    private boolean isNeedOtto = false;
    private ImageView left_button;
    private TextView header_title;
    private ImageView right_button;
    private ACache aCache;
    private Gson gson;
    private Handler handler;

    private static LoginResponse loginResponse =
            new Gson().fromJson(ACache.get(BaojianApplication.getInstance()).getAsString(LoginResponse.TAG),
                    LoginResponse.class);

    public static boolean isCallBusy = false;
    public boolean isDestroyed = false;

    public static RtcEngine rtcEngine;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        setContentView(getContentView());

        initAgora();

        initCommonHeader();

        initData();
    }

    private void initAgora() {
        if(rtcEngine == null) {
            try {
                rtcEngine = RtcEngine.create(BaojianApplication.getInstance(), ConstValue.AGORA_APPID, iRtcEngineEventHandler);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }

    private void initCommonHeader() {
        left_button = (ImageView) findViewById(R.id.left_button);
        header_title = (TextView) findViewById(R.id.header_title);
        right_button = (ImageView) findViewById(R.id.right_button);
        if (left_button != null && header_title != null){
            left_button.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    onBackPressed();
                }
            });
            header_title.setText(getTitle());
        }
        hideHeaderRightBtn();
    }

    @Override
    public void setTitle(CharSequence title) {
        super.setTitle(title);

        if(this.header_title != null)
            this.header_title.setText(title);
    }

    @Override
    protected void onStart() {
        super.onStart();

        if(isNeedOtto) {
            try {
                AppBus.getInstance().register(this);
            } catch (IllegalArgumentException e){}
        }
    }

    @Override
    protected void onDestroy() {
        if(isNeedOtto)
            AppBus.getInstance().unregister(this);

        super.onDestroy();

        isDestroyed = true;
    }

    public void onResume() {
        super.onResume();
        MobclickAgent.onResume(this);
    }
    public void onPause() {
        super.onPause();
        MobclickAgent.onPause(this);
    }

    public void startActivity(Class clazz){
        Intent intent = new Intent(this, clazz);
        startActivity(intent);
    }

    public void startActivity(Class clazz, Bundle extras){
        Intent intent = new Intent(this, clazz);
        intent.putExtras(extras);
        startActivity(intent);
    }

    public void initData(){

    }

    protected void needOtto(){
        isNeedOtto = true;
    }

    protected ImageView getHeaderLeftBtn(){
        return left_button;
    }

    protected ImageView getHeaderRightBtn(){
        return right_button;
    }

    protected void hideHeaderRightBtn(){
        if(right_button != null)
            right_button.setVisibility(View.GONE);
    }

    protected void hideHeaderLeftBtn(){
        if(left_button != null)
            left_button.setVisibility(View.GONE);
    }

    protected void showHeaderRightBtn(){
        if(right_button != null)
            right_button.setVisibility(View.VISIBLE);
    }

    protected void showHeaderLeftBtn(){
        if(left_button != null)
            left_button.setVisibility(View.VISIBLE);
    }

    protected void toast(String s){
        Toast.makeText(this, s, Toast.LENGTH_SHORT).show();
    }

    protected void toastFullscreen(String s){
        CustomToast.showToast(this, s);
    }

    private LoadingDialog loadingDialog;
    protected void waiting(String msg){
        if(loadingDialog == null)
            loadingDialog = new LoadingDialog(this, msg);
        loadingDialog.setMsg(msg);
        loadingDialog.show();
    }
    protected  void stopWaiting(){
        if(loadingDialog == null)
            return;
        loadingDialog.close();
    }

    private YesOrNoDialog yesOrNoDialog;
    protected void showYesOrNoDialog(String msg, YesOrNoDialog.OnClickListener listener){
        showYesOrNoDialog(msg, "取消", "确定", listener);
    }
    protected void showYesOrNoDialog(String msg, String left, String right, YesOrNoDialog.OnClickListener listener){
        yesOrNoDialog = new YesOrNoDialog(this, msg, left, right, listener);
        yesOrNoDialog.show();
    }

    private OkDialog okDialog;
    protected void showOkDialog(String msg, OkDialog.OnClickListener listener){
        if(okDialog == null){
            okDialog = new OkDialog(this, msg, listener);
        }
        okDialog.show();
    }

    private ImageSelectDialog imageSelectDialog;
    protected void showImageSelectDialog(ImageSelectDialog.OnImageSelectListener listener){
        if(imageSelectDialog == null){
            imageSelectDialog = new ImageSelectDialog(this, listener);
        }
        imageSelectDialog.show();
    }

    private SendGiftsDialog sendGiftsDialog;
    protected void showSendGiftsDialog(long uid, int yue, SendGiftsDialog.OnSendListener listener){
        sendGiftsDialog = new SendGiftsDialog(this, uid, yue, listener);
        sendGiftsDialog.show();
    }

    public abstract int getContentView();

    public ACache getACache(){
        if(aCache == null)
            aCache = ACache.get(this);
        return aCache;
    }

    protected Gson getGson(){
        if(gson == null)
            gson = new Gson();
        return gson;
    }

    protected String getAbsoluteImagePath(Uri uri)
    {
        // can post image
        String [] proj={MediaStore.Images.Media.DATA};
        Cursor cursor = managedQuery( uri,
                proj,       // Which columns to return
                null,       // WHERE clause; which rows to return (all rows)
                null,       // WHERE clause selection arguments (none)
                null);      // Order-by clause (ascending by name)


        int column_index = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
        cursor.moveToFirst();

        return cursor.getString(column_index);
    }

    private static IRtcEngineEventHandler iRtcEngineEventHandler = new IRtcEngineEventHandler() {
        @Override
        public void onConnectionLost() {
            AppBus.getInstance().post("onConnectionLost");
            Log.e("onConnectionLost", "");
        }


        public void onJoinChannelSuccess(String channel, int uid, int elapsed) {
            Log.e("onJoinChannelSuccess", "");
        }

        public void onRejoinChannelSuccess(String channel, int uid, int elapsed) {
            Log.e("onRejoinChannelSuccess", "");
        }

        public void onWarning(int warn) {
            Log.e("onWarning", "" + warn);
        }

        public void onError(int err) {
            Log.e("onError", "" + err);
        }

        public void onApiCallExecuted(String api, int error) {
        }

        public void onAudioQuality(int uid, int quality, short delay, short lost) {
        }

        public void onLeaveChannel(IRtcEngineEventHandler.RtcStats stats) {
        }

        public void onRtcStats(IRtcEngineEventHandler.RtcStats stats) {
        }

        public void onAudioVolumeIndication(IRtcEngineEventHandler.AudioVolumeInfo[] speakers, int totalVolume) {
        }

        public void onNetworkQuality(int uid, int txQuality, int rxQuality) {
        }

        public void onLastmileQuality(int quality) {
        }

        public void onUserJoined(int uid, int elapsed) {
        }

        public void onUserOffline(int uid, int reason) {
        }

        public void onUserMuteAudio(int uid, boolean muted) {
        }

        public void onConnectionInterrupted() {
        }

        public void onRefreshRecordingServiceStatus(int status) {
        }

        public void onStreamMessage(int uid, int streamId, byte[] data) {
        }

        public void onStreamMessageError(int uid, int streamId, int error, int missed, int cached) {
        }

        public void onMediaEngineLoadSuccess() {
        }

        public void onMediaEngineStartCallSuccess() {
        }

        public void onAudioMixingFinished() {
        }

        public void onRequestChannelKey() {
        }

        public void onAudioRouteChanged(int routing) {
        }
    };

    private MediaPlayer mPlayer;
    protected void playAudio(File file){
        mPlayer = new MediaPlayer();
        try{
            mPlayer.setDataSource(file.getAbsolutePath());
            mPlayer.prepare();
            mPlayer.start();
        }catch(IOException e){
        }
    }
    protected void stopPlayAudio(){
        if(mPlayer != null)
            mPlayer.release();
        mPlayer = null;
    }

    public static LoginResponse getLoginResponse(){
        if(loginResponse == null){
            loginResponse =
                    new Gson().fromJson(ACache.get(BaojianApplication.getInstance()).getAsString(LoginResponse.TAG),
                            LoginResponse.class);
        }
        return loginResponse;
    }
    public static void updateLoginResponse(){
        loginResponse =
                new Gson().fromJson(ACache.get(BaojianApplication.getInstance()).getAsString(LoginResponse.TAG),
                        LoginResponse.class);
    }
    public static void logout(){
        BaojianApplication.getInstance().turnOffPush();
        Api.getInstance().cancelAllRequest();
        Api.getInstance().clearCookie();
        BaojianApplication.getInstance().pushService.unbindAccount(new CommonCallback() {
            @Override
            public void onSuccess(String s) {

            }

            @Override
            public void onFailed(String s, String s1) {

            }
        });
        ACache.get(BaojianApplication.getInstance()).remove("mobile_token");
        ACache.get(BaojianApplication.getInstance()).put(LoginResponse.TAG, "");
        loginResponse = null;
        AgoraHelper.getInstance().agoraAPI.logout();
    }
    public static void initLogin(){
        BaojianApplication.getInstance().turnOnPush();
        loginResponse =
                new Gson().fromJson(ACache.get(BaojianApplication.getInstance()).getAsString(LoginResponse.TAG),
                        LoginResponse.class);
    }

    protected Handler getHandler(){
        if(handler == null)
            handler = new Handler();
        return handler;
    }
}
